<template>
  <div id="addQuestionPage">
    <h2 style="margin-bottom: 36px; text-align: center">设置题目</h2>
    <a-form
      :model="questionContent"
      style="max-width: 480px; margin: 0 auto"
      @submit="handleSubmit"
      auto-label-width
      lebal-align="left"
    >
      <a-form-item label="应用ID"> {{ appId }}</a-form-item>
      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space size="large">
          <a-button @click="addQuestion(questionContent.length)" type="primary"
            >底部添加题目
          </a-button>
          <!--   AI生成题目    -->
          <AiGenerateQuestionDrawer
            :app-id="appId"
            :on-success="onAiGenerateSuccess"
            :onSSESuccess="onAiGenerateSuccessSSE"
            :onSSEClose="onSSEClose"
            :onSSEStart="onSSEStart"
          />
        </a-space>
        <!--遍历每个题目-->
        <div v-for="(question, index) in questionContent" :key="index">
          <a-space>
            <h3>题目{{ index + 1 }}</h3>
            <a-button
              size="small"
              @click="addQuestion(index + 1)"
              status="warning"
              >添加题目
            </a-button>
            <a-button
              size="small"
              @click="deleteQuestion(index)"
              :style="{ marginLeft: '10px' }"
              status="danger"
              >删除题目
            </a-button>
          </a-space>
          <a-form-item field="posts.post1" :label="`题目 ${index + 1} 标题`">
            <a-input v-model="question.title" placeholder="请输入标题" />
          </a-form-item>
          <!--遍历每个题目选项-->
          <a-space>
            <h3>题目{{ index + 1 }}选项列表</h3>
            <a-button
              size="small"
              @click="addQuestionOption(question, index + 1)"
              status="warning"
              >底部添加选项
            </a-button>
          </a-space>
          <a-form-item
            v-for="(option, optionIndex) in question.options"
            :label="`选项${optionIndex + 1}`"
            :key="optionIndex"
            :content-flex="false"
            :merge-props="false"
          >
            <a-form-item label="选项key">
              <a-input v-model="option.key" placeholder="请输入选项的key" />
            </a-form-item>
            <a-form-item label="选项value">
              <a-input v-model="option.value" placeholder="请输入选项的value" />
            </a-form-item>
            <a-form-item label="选项结果">
              <a-input v-model="option.result" placeholder="请输入选项的结果" />
            </a-form-item>
            <a-form-item label="选项得分">
              <a-input v-model="option.score" placeholder="请输入选项的得分" />
            </a-form-item>
            <a-space>
              <a-button
                size="small"
                @click="addQuestionOption(question, optionIndex + 1)"
                status="warning"
                >添加选项
              </a-button>
              <a-button
                size="small"
                @click="deleteQuestionOption(question, optionIndex + 0)"
                :style="{ marginLeft: '10px' }"
                status="danger"
                >删除选项
              </a-button>
            </a-space>
          </a-form-item>
          <a-divider :margin="10">
            <icon-star />
          </a-divider>
        </div>
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" type="primary">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, watchEffect, withDefaults } from "vue";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import API from "@/api";
import {
  addQuestionUsingPost,
  editQuestionUsingPost,
  getQuestionVoByIdUsingGet,
} from "@/api/questionController";
import AiGenerateQuestionDrawer from "@/view/add/components/AiGenerateQuestionDrawer.vue";

interface Props {
  appId: any;
}

const questionContent = ref<API.QuestionContentDTO[]>([]);
/**
 * 添加题目
 */
const addQuestion = (index: number) => {
  questionContent.value.splice(index, 0, {
    title: "",
    options: [],
  });
};

/**
 * 删除题目
 * @param index
 */
const deleteQuestion = (index: number) => {
  questionContent.value.splice(index, 1);
};

/**
 * 添加题目选项
 * @param index
 */
const addQuestionOption = (question: API.QuestionContentDTO, index: number) => {
  question.options?.splice(index, 0, {
    key: "",
    result: "",
    score: 0,
    value: "",
  });
};

/**
 * 删除题目选项
 * @param index
 */
const deleteQuestionOption = (
  question: API.QuestionContentDTO,
  index: number
) => {
  question.options?.splice(index, 1);
};
const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return 0;
  },
});

/**
 * 加载数据
 */
const oldQuestionData = ref<API.QuestionVO>({});
const loadData = async () => {
  if (!props.appId) {
    return;
  }
  const res = await getQuestionVoByIdUsingGet({ id: props.appId });
  if (res.data.code === 0) {
    oldQuestionData.value = res.data.data || {};
    questionContent.value = res.data.data?.questionContent || [];
    console.log(res.data.data);
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};
watchEffect(() => {
  loadData();
});
/**
 * 表单信息
 */
const router = useRouter();

/**
 * 提交表单
 * @param data
 */
const handleSubmit = async () => {
  if (!props.appId) {
    return;
  }
  let res: any;
  if (props.appId) {
    res = await editQuestionUsingPost({
      id: oldQuestionData.value?.id || props.appId,
      questionContent: questionContent.value,
    });
  } else {
    res = await addQuestionUsingPost({
      appId: props.appId,
      questionContent: questionContent.value,
    });
  }
  if (res.data.code === 0) {
    message.success("操作成功,跳转值详情页...");
    setTimeout(() => {
      router.push(`/app/detail/${props.appId ?? res.data.data}`);
    }, 2000);
  } else {
    message.error("操作失败，" + res.data.message);
  }
};
const onAiGenerateSuccess = (result: API.QuestionContentDTO[]) => {
  questionContent.value = result;
};

/**
 * AI 生成题目成功后执行（SSE）
 */
const onAiGenerateSuccessSSE = (result: API.QuestionContentDTO) => {
  questionContent.value = [...questionContent.value, result];
};

/**
 * SSE 开始生成
 * @param event
 */
const onSSEStart = (event: any) => {
  message.success("开始生成");
};

/**
 * SSE 生成完毕
 * @param event
 */
const onSSEClose = (event: any) => {
  message.success("生成完毕");
};
</script>
